import ManacoEditor, { OnMount, EditorProps } from '@monaco-editor/react'
import { editor } from "monaco-editor"

export interface EditorFile {
    name: string,
    value: string,
    language: string
}

interface Props {
    value: string
    width?: string
    height?: string
    onChange?: EditorProps['onChange']
    options?: editor.IStandaloneEditorConstructionOptions // 编辑器配置
    defaultOptions?: Record<string, any>
}

export function CodeEditor(props: Props){

    const { value, width="100%", height="100%", onChange, options, defaultOptions = {
        path: "componenet.css",
        language: "css"
    } } = props


    // 挂载时：给编辑器添加了一个快捷键绑定，当用户按下Ctrl+J（或Cmd+J在Mac上）时，会触发代码格式化操作。
    const handleMount: OnMount = (editor, monaco) => {
        editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyJ, () => {
            editor.getAction('editor.action.formatDocument')?.run()
        });
    }

    return (
        <ManacoEditor
            width={ width }
            height={ height }
            path={defaultOptions.path }
            defaultLanguage={defaultOptions.language}
            value={value}
            onChange={onChange}
            onMount={handleMount}
            options={{
                fontSize: 14,
                scrollBeyondLastLine: false,
                fixedOverflowWidgets: true, // 超出编辑器大小的使用fixed属性显示
                minimap: {
                    enabled: false // 缩略图
                },
                scrollbar: {
                    verticalScrollbarSize: 6,
                    horizontalScrollbarSize: 6
                },
                ...options
            }}
        />
    )
}